import {
  createMemo,
  createSignal,
  mergeProps,
  Show,
  splitProps,
  type ParentComponent,
} from "solid-js";
import type { FcCheckboxProps } from "./types";
import { wrapClasses } from "@lib/types";
import { GetElementRef } from "../directives";
import type { JSX } from "solid-js/jsx-runtime";

const getRef = GetElementRef;
const defaultProps: Partial<FcCheckboxProps> = {
  type: "checkbox",
};
const FcCheckBox: ParentComponent<FcCheckboxProps> = (props) => {
  const [local, elProps] = splitProps(mergeProps(defaultProps, props), [
    "children",
    "classList",
    "value",
    "onValueChanged",
    "ref",
    "$ServerOnly",
    "checked",
    "type",
    "inline",
    "reverse",
  ]);

  const classList = createMemo(() => wrapClasses(local.classList));
  const containerClassList = createMemo(() => {
    return {
      ["form-switch"]: local.type === "switch",
      ["form-check-inline"]: local.inline,
      ["form-check-reverse"]: local.reverse,
    };
  });

  const [ref, setRef] = createSignal<HTMLInputElement | undefined>(undefined);
  const handleChecked: JSX.InputHTMLAttributes<HTMLInputElement>["onChange"] = (
    e
  ) => {
    const el = ref();
    if (el) {
      local.onValueChanged?.(el.checked);
      _setChecked(el.checked);
    }
  };

  const type = createMemo(() => {
    if (local.type === "radio") {
      return "radio";
    } else {
      return "checkbox";
    }
  });

  const [_checked, _setChecked] = createSignal(local.value ?? local.checked);

  const value = createMemo(() => {
    if (local.value === undefined) {
      return _checked();
    }
    return local.value;
  });

  const checkbox = (
    <input
      ref={local.ref}
      class="form-check-input"
      {...elProps}
      type={type()}
      checked={value()}
      classList={classList()}
      onChange={handleChecked}
      use:getRef={setRef}
    ></input>
  );

  return (
    <Show when={local.children !== undefined} fallback={checkbox}>
      <div class="form-check" classList={containerClassList()}>
        {checkbox}
        <label class="form-check-label" for={elProps.id}>
          {local.children}
        </label>
      </div>
    </Show>
  );
};

export type * from "./types";
export default FcCheckBox;
